<style>
    .edit .ant-form-item-control{
        line-height: 100%;
    }
    .img img{
        width: 50px;
        height: 50px;
    }
    .spec-list .ant-table table{
        border-left: 1px solid #e2e2e2;
    }
    .spec-list .info{
        margin-left:10px;
        text-align: left;
        line-height: 1.8;
    }
    .spec-list .goods div{
        float: left;
    }
</style>
<template>
    <div class="page-container is-form">
        <a-spin :spinning="spinning">
            <a-form :layout="formLayout" :form="form">
                <a-form-item label='商品编码'  v-bind="formItemLayout">
                    <a-input-search  placeholder='请输入商品编码'
                                    @search="onCreateBarCode"  style="width: 300px;"
                                    v-decorator="['barCode',{rules: [{ required: true, message: '商品编码不能为空!' }]}]">
                        <a-button type="primary"  slot="enterButton">生成</a-button>
                    </a-input-search>
                </a-form-item>
                <a-form-item label='商品名称'  v-bind="formItemLayout">
                    <a-input placeholder='请输入商品名称' v-decorator="['name',{rules: [{ required: true, message: '商品名称不能为空!' }]}]" style="width: 300px;"/>
                </a-form-item>
                <a-form-item label='商品主图' v-bind="formItemLayout" help="建议图片 JPG、PNG、GIF格式，小于500k">
                    <a-upload  listType="picture-card"
                               :fileList="fileList"  @preview="handlePreview"
                               :action="uploadAction"  @change="handleChange">
                        <div v-if="fileList.length < 1">
                            <a-icon type="plus" />
                            <div class="ant-upload-text">上传</div>
                        </div>
                    </a-upload>
                    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                        <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
<!--                    <a-input type="hidden" v-decorator="['mainImage',{rules: [{ required: true, message: '请上传商品主图!' }]}]" />-->
                </a-form-item>
                <a-form-item label='商品分类' v-bind="formItemLayout">
                    <a-select v-decorator="['goodsTypeId',{rules: [{ required: true, message: '请选择分类!' }]}]" placeholder="请选择分类" style="width: 300px">
                        <a-select-option :value="item.id" v-for="item in typeList" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
<!--                    <a-cascader expandTrigger="hover" :options="typeList" :fieldNames="typeField" v-decorator="['goodsTypeId',{rules: [{ required: true, message: '请选择分类!' }]}]" placeholder="请选择分类" style="width: 300px;"/>-->
                </a-form-item>
                <a-form-item label='单位'  v-bind="formItemLayout">
                    <a-select v-decorator="['unitId',{rules: [{ required: true, message: '请选择单位!' }]}]"  style="width: 300px" placeholder='请选择单位'>
                        <a-select-option v-for="unit in unitList" :value="unit.id" :title="unit.name">
                            <span>{{unit.name}}</span>
                            <span class="default_tips" style="position:absolute;right:20px;top:5px;" v-if="unit.mode =='WEIGHT'">计重</span>
                            <span class="default_tips"  style="position:absolute;right:20px;top:5px;" v-if="unit.mode =='NUMBER'">计数</span>
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label='规格'  v-bind="formItemLayout">
                    <a-button type="default" @click="onAddSpec"><a-icon type="plus" /> 新增规格</a-button>
                </a-form-item>
                <a-row class="spec-list">
                    <a-col :offset="4" :span="18">
                        <a-table bordered :columns="columns" :dataSource="specList" :pagination="false" :loading="loading" :rowKey="record => record.id || record.barCode" size="middle">
                            <template slot="index" slot-scope="text,record,index">
                                {{index+1}}
                            </template>
                            <template slot-scope="text,record" slot="name">
                                <div class="goods clearfix">
                                    <div class="img">
                                        <img v-if="record.mainImage && record.mainImage!='' " :src="record.mainImage" />
                                        <img v-else src="@/assets/images/mainImage.jpg" />
                                    </div>
                                    <div class="info">
                                        <p>{{record.name}}</p>
                                    </div>
                                </div>
                            </template>
                            <template slot="price" slot-scope="price">
                                {{fmMoney(price,2,true)}}
                            </template>
                            <template slot="operation" slot-scope="text,record,index">
                                <a @click="onEdit(index,record)"  class="ant-btn-text"><a-icon type="form" /></a>
                                <a-divider type="vertical" />
                                <a @click="onDeleted(index,record)"  class="ant-btn-text"><a-icon type="delete" /></a>
                            </template>
                        </a-table>
                    </a-col>

                </a-row>
                <a-form-item label='商品详细信息'  v-bind="formItemLayout" class="edit">
                    <edit :goodsContent="goodsContent" @result="updateContent"></edit>
                    <a-input v-decorator="['content']" type="hidden" />
                </a-form-item>
                <a-form-item :wrapperCol="{span:8,offset: 4}">
                    <a-button type='primary'  :loading="bntLoading" @click="onSubmit">保 存</a-button>
                </a-form-item>
            </a-form>


        </a-spin>
        <a-modal title="新增规格" v-model="specAddVisible" :footer="null">
            <goods-spec-add :goods-id="params.id" :spec-length="specList.length" v-if="specAddVisible" @save="handleSaveEmit"></goods-spec-add>
        </a-modal>
        <a-modal title="编辑规格" v-model="specEditVisible" :footer="null">
            <goods-spec-edit :model="editSpec" v-if="specEditVisible" @save="handleSaveEmit"></goods-spec-edit>
        </a-modal>
    </div>
</template>
<script>
    import {save,findDetail} from "@/api/goods";
    import {findList as findUnitList} from "@/api/goodsUnit";
    import {findWaterList as findGoodsTypeList} from "@/api/goodsType";
    import Edit from '@/components/editor/index';
    import { mapGetters } from 'vuex';
    import {fmMoney} from "@/utils/index";
    import GoodsSpecAdd from './GoodsSpecAdd'
    import GoodsSpecEdit from './GoodsSpecEdit'

    const columns = [
        {title: '序号', dataIndex: 'index',width: 60,align:'center',scopedSlots: { customRender: 'index' }},
        {title: '规格名称',dataIndex: 'name',scopedSlots: { customRender: 'name' }},
        {title: '价格',dataIndex: 'price',width: 150,align:'right',scopedSlots: { customRender: 'price' }},
        {title: '库存',dataIndex: 'stock',width: 150,align:'right'},
        {title: '操作',key: 'operation',align:'center',width: 100,scopedSlots: { customRender: 'operation' }}];
    export default {
        components: {Edit,GoodsSpecAdd,GoodsSpecEdit},
        beforeCreate(){
            this.form = this.$form.createForm(this);
        },
        data() {
            return{
                columns,
                formLayout:'horizontal',
                spinning:false,
                params:{
                    id:0,
                },
                loading:false,
                typeField:{
                    label: 'name', value: 'id', children: 'children'
                },
                unitList:[],
                typeList:[],
                bntLoading:false,
                uploadAction:this.UPLOAD_URL,
                mainImage:'',
                fileList: [],
                previewVisible: false,
                previewImage: '',
                goodsContent:'',
                model:{},
                specAddVisible: false,
                specEditVisible: false,
                editSpec: null,
                specList:[],
                delSpecList:[]
            }
        },
        computed: {
            formItemLayout () {
                const { formLayout } = this
                return formLayout === 'horizontal' ? {
                    labelCol: { span:4},
                    wrapperCol: { span:18 },
                } : {}
            },
            ...mapGetters([
                'companyId'
            ]),
        },
        methods:{
            fmMoney,
            updateContent(r){
                this.form.setFieldsValue({'content': r});
            },
            handleCancel() {
                this.previewVisible = false
            },
            handlePreview(file) {
                this.previewImage = file.url || file.thumbUrl
                this.previewVisible = true
            },
            handleChange({file, fileList}) {
                this.loading = true
                if(file.status == 'removed') this.form.setFieldsValue({'mainImage':''});
                if(file.status == 'uploading') {
                    const isJPG = file.type === 'image/jpeg';
                    const isPNG = file.type === 'image/png';
                    const isGif = file.type === 'image/gif';
                    if (!isJPG && !isPNG && !isGif) {
                        this.$message.error('图片格式错误,请检查后重新上传!');
                        this.loading = false;
                        return;
                    }
                    const isLt500KB = file.size / 1024 / 500
                    if (!isLt500KB) {
                        this.$message.error('图片大小不合适,请上传小于500KB的图片!');
                        this.loading = false;
                        return;
                    }
                }
                this.fileList = fileList;
                // 根据服务端返回数据筛选上传成功的文件
                fileList.forEach((file) => {
                    if (file.response) {
                        this.form.setFieldsValue({'mainImage': file.response.data});
                    }
                });
                this.loading = false;
            },
            //新增规格
            onAddSpec(){
                this.specAddVisible = true
            },
            //编辑
            onEdit(index,item) {
                this.editSpec = {...item, index: index}
                this.specEditVisible = true
            },
            onDeleted(index,item){
                let _this = this;
                this.$confirm({
                    title: '确认删除该商品规格吗?',
                    okText: '确认',
                    okType: 'danger',
                    cancelText: '取消',
                    onOk() {_this.handleDelete(index,item);},
                    onCancel() {},
                });
            },
            async handleDelete(index,item){
                if(item.id != null && item.id != undefined){
                    item.deleted='DELETED'
                    this.delSpecList.push(item)
                }
                this.specList.splice(index,1)
            },
            onCreateBarCode(){
                var str = new Date().getTime().toString();
                var s = str.substr(str.length-4,str.length-1);
                var companyId  = this.companyId+"";

                if(this.companyId<10){
                    companyId = "0"+companyId;
                }else{
                    companyId = companyId.substr(companyId.length-2,companyId.length)
                }
                var seconds = new Date().getSeconds();
                if(seconds<10) seconds = "0"+seconds;
                var date = new Date().getDate();
                if(date < 10) date = "0"+date;
                var barCode = "H"+companyId+seconds+"18"+s+date;
                this.form.setFieldsValue({'barCode':barCode});
            },
            handleSaveEmit(type,result){
                if(type === 'add'){
                    result.barCode = this.onCreateBarCode()
                    this.specList.push(result)
                }
                else{
                    this.specList[result.index] = result
                }
                this.specAddVisible = false;
                this.specEditVisible = false;
            },
            onSubmit(){
                this.bntLoading = true;
                this.form.validateFields(
                    (err,values) => {
                        if (!err) {
                            this.onSave(values);
                        }else{
                            this.bntLoading = false;
                        }
                    },
                )
            },
            async onSave(data){
                this.spinning = true;
                let form = {...this.model,...data,specList:this.specList.concat(this.delSpecList)}
                let resp = await save(form);
                this.spinning = false;
                let _this = this;
                if(this.qUtil.validResp(resp)){
                    this.$success({title:'保存成功!',okText:'确定',
                        onOk(){_this.$router.push({name:'WaterGoodsList'});}
                    });
                }else{
                    this.$error({title: resp.msg, okText: '确定'});
                    this.bntLoading = false;
                }
            },
            async onLoadUnitList(){
                let resp = await findUnitList();
                if(this.qUtil.validResp(resp)){
                    this.unitList = resp.data.unitList;
                }
            },
            async onLoadTypeList(){
                let resp = await findGoodsTypeList({status: 'AVAILABLE'})
                if(this.qUtil.validResp(resp)){
                    this.typeList = resp.data.dataList || []
                }
            },
            async onLoad(){
                if(this.params.id == 0) return false;
                let resp = await findDetail(this.params.id);
                if(this.qUtil.validResp(resp)){
                    this.model = resp.data.goods;
                    const {barCode,name,spec,unitId,goodsTypeId,mainImage,content} = resp.data.goods;
                    this.form.setFieldsValue({barCode,name,spec,unitId,goodsTypeId,mainImage,content});
                    this.goodsContent = content;
                    this.specList = resp.data.specList || [];
                    this.specList.map(m=>{
                        m.barCode = this.onCreateBarCode();
                    })
                    if (mainImage) {
                        this.fileList.push({
                            uid: '-1',
                            name: ' ',
                            status: 'done',
                            url: resp.data.goods.mainImage
                        })
                    }
                }
            }
        },
        mounted(){
            this.params.id = parseInt(this.$route.params.id) || 0;
            this.onLoadUnitList();
            this.onLoadTypeList();
            this.onLoad();
        },
    }
</script>